package com.pan.kang.controller;

import cn.hutool.core.date.DateUtil;
import com.pan.kang.common.Request;
import com.pan.kang.common.jwt.JwtConstants;
import com.pan.kang.common.jwt.JwtUser;
import com.pan.kang.common.jwt.JwtUtil;
import com.pan.kang.dto.LoginDto;
import com.pan.kang.entity.UserEntity;
import com.pan.kang.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    public static final long EXPIRES_MIN = 7L * 24 * 60;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserRepository userRepository;

    /**
     * 登录
     */
    @PostMapping("/V1.0/login")
    public void login(@RequestBody Request<LoginDto> request) {
        LoginDto loginDto = request.getData();
        String phone = loginDto.getPhone();
        String code = stringRedisTemplate.opsForValue().get(phone);
        // 判断短信验证码是否过期
        if (code == null || code.isEmpty()) {
            throw new RuntimeException("短信验证码已过期！！！");
        }
        if (!code.equals(loginDto.getValidCode())) {
            throw new RuntimeException("短信验证码不正确！！！");
        }
        // 根据电话号码获取用户信息
        List<UserEntity> userEntityList = userRepository.getUserEntityByMobile(phone);
        if (CollectionUtils.isEmpty(userEntityList)) {
            throw new RuntimeException("手机号码未注册，请先注册！！！");
        }
        UserEntity user = userEntityList.get(0);
        // 用户登录之后将 userId 及对应的 JWT信息（token）存储redis中（默认7天），每次用户请求其它接口，需要在请求头中携带Token
        JwtUser jwtUser = new JwtUser();
        jwtUser.setUserId(user.getId());
        jwtUser.setNickname(user.getMobile());
        jwtUser.setExpiresMin(EXPIRES_MIN);
        jwtUser.setIssuedAt(DateUtil.date());
        String token = JwtUtil.createToken(jwtUser);

        // key:PROJECT:JWT:TOKEN: + userId value: token 存储 redis
        stringRedisTemplate.opsForValue().set(JwtConstants.JWT_TOKEN_KEY.concat(jwtUser.getUserId()),
                token, EXPIRES_MIN, TimeUnit.MINUTES);
    }


    /**
     * 模拟发送验证码，用户登录需要短信验证码，1分钟之后过期
     */
    @PostMapping("/V1.0/sendCode")
    public void sendCode(@RequestBody Request<LoginDto> request) {
        LoginDto loginDto = request.getData();
        String phone = loginDto.getPhone();
        String validCode = loginDto.getValidCode();
        stringRedisTemplate.opsForValue().set(phone, validCode, 1L, TimeUnit.MINUTES);
    }


}
